package field;
import geom.Segment;
import geom.Vector;
import processing.core.PApplet;


public class BinGrid {
	Bin[][] bins;
	Vector binSize; 
	Vector numBins;
	Vector offset;
	public BinGrid(Vector offset, Vector size, Vector numBins){
		this.bins = new Bin[(int)numBins.x][(int)numBins.y];
		this.numBins = numBins;
		this.offset = offset;
		binSize = new Vector(size.x / numBins.x, size.y / numBins.y, 0);
		for(int x = 0; x < numBins.x; x++){
			for(int y = 0; y < numBins.y; y++){
				this.bins[x][y] = new Bin(new Vector(x * binSize.x, y * binSize.y, 0).add(offset), binSize, new Vector(x, y, 0));
			}
		}
	}
	
	public Bin getBinFor(Vector v){
		Vector binPos = v.sub(offset).div(binSize);
		//PApplet.println("Offset " + offset);
		//PApplet.println("binPos: " + binPos + " pos " + v);
		int x = (int)Math.floor(binPos.x);
		int y = (int)Math.floor(binPos.y);
		if(x >= numBins.x || y >= numBins.y || x < 0 || y < 0)
			return null;
		return bins[x][y];
	}
	
	public void add(Segment seg){
		Bin startBin = getBinFor(seg.startPos());
		Bin endBin = getBinFor(seg.endPos());
		if(startBin == null) startBin = endBin;
		if(endBin == null) endBin = startBin;
		if(endBin == null && startBin == null) return;
		
		for(int x = (int)startBin.arrayPos.x; x <= endBin.arrayPos.x; x++){
			for(int y = (int)startBin.arrayPos.y; y <= endBin.arrayPos.y; y++){
				bins[x][y].add(seg);
			}
		}

		
	}
	
	public void draw(PApplet pa){
		for(int x = 0; x < numBins.x; x++){
			for(int y = 0; y < numBins.y; y++){
				pa.rect(bins[x][y].lower.x, bins[x][y].lower.y, bins[x][y].width(), bins[x][y].height());
			}
		}
	}
}
